package LineCode.剑指Offer.举例让抽象具体化;

import LineCode.剑指Offer.Utils.TreeNodeUtil;
import LineCode.剑指Offer.dto.TreeNode;

import java.util.*;

/**
 * 从上往下打印出二叉树的每个节点，同层节点从左至右打印。
 */
public class 从上往下打印二叉树 {

    public static void main(String[] args) {
        TreeNode test = TreeNodeUtil.getOneTest1();
        for (Integer x : PrintFromTopToBottom(test)) {
            System.out.print(x);
        }
    }

    public static ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
        //TreeNode last = root, nlast;
        ArrayList<Integer> result = new ArrayList<>();
        if (root == null) return result;
        Queue<TreeNode> items = new LinkedList();
        items.offer(root);
        while(!items.isEmpty()) {
            if (items.peek().left != null)
                items.offer(items.peek().left);
            if (items.peek().right != null)
                items.offer(items.peek().right);
            result.add(items.poll().val);
        }
        return result;
    }

}
